package cn.community.system.advice;

import cn.community.system.exception.LogicException;
import cn.community.system.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 通用异常处理类
 * 请求进入controller映射方法之前做功能增强：日期格式化（dateFormat）等
 * 请求进入controller映射方法之后做功能增强：统一异常处理等
 */
@ControllerAdvice   // 功能增强注解，动态代理controller类实现的一些额外的功能
public class CommonsExceptionHandler {

    @ExceptionHandler(LogicException.class)  // 捕获用户异常
    @ResponseBody
    public Object LogicExceptionHandler(Exception e, HttpServletResponse response){
        e.printStackTrace();
        response.setContentType("application/json;charset=utf-8");
        return JsonResult.error(JsonResult.CODE_ERROR_PARAM,e.getMessage(),null);
    }

    @ExceptionHandler(RuntimeException.class)  // 捕获系统异常
    @ResponseBody
    public Object RuntimeExceptionHandler(Exception e, HttpServletResponse response){
        e.printStackTrace();
        response.setContentType("application/json;charset=utf-8");
        return JsonResult.defaultError();
    }

    /***
     * 处理没有权限的异常
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler(UnauthorizedException.class)
    public Object handleUnauthorizedException(Exception e, Model model, HandlerMethod handlerMethod, HttpServletResponse response) throws IOException {
        //把异常信息打印出,方便我们开发的时候找bug
        e.printStackTrace();
        //判断当前执行的方法是否是ajax的方法(@ResponseBody)
        if(handlerMethod.hasMethodAnnotation(ResponseBody.class)){
            //如果是,则返回jsonresult
            JsonResult json = JsonResult.error(JsonResult.CODE_ERROR_NOPERMISSION,JsonResult.MSG_NOPERMISSION,null);
            //使用response对象输出数据(json字符串)
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(json));
            return null;
        }
        //如果不是,则返回错误视图
        model.addAttribute("ex", e);
        return "common/nopermission"; //返回的错误视图
    }
}
